<template>
    <div dir="scfs">
        <div class="bg-container">
            <!-- 生产方式 -->
            <div class="my-header">
                <div class="my-tool-bar">
                    <div class="bg-container-1">
                        <div>
                            <el-button type="primary" :icon="Search" class="stbutencx" @click="selectHandler">查询</el-button>
                            <el-button type="success" :icon="CirclePlus" class="stbutenxz"
                                @click="addHandler">新增</el-button>
                            <el-button plain :icon="Delete" @click="deleteHandler">删除</el-button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="gang"></div>

        <div ref="tablediv" style="padding: 10px; box-sizing: border-box;min-height:100%;background-color: #fff;">

            <AgGridVuesCopys style="height:72vh;" class="ag-theme-alpine " :columnDefs="tc" :rowData="tableCon.tableConter"
                :defaultColDef="defaultColDef" rowSelection="multiple" @grid-ready="gridReady" :suppressCopyRowsToClipboard="true">
            </AgGridVuesCopys>

            <div class="pagings">
                <paginationCopys :total="paging.total" v-model:current='pages' show-page-size show-total show-jumper :page-size="paging.size"
                    size="mini" @change="pagingChange" @page-size-change="pagingSizeChange" :suppressCopyRowsToClipboard="true"/>
            </div>
        </div>
        <!-- <AgGridVuesCopys style=" height:400px;" class="ag-theme-alpine" :columnDefs="columnDefs" :rowData="rowData"
        :defaultColDef="defaultColDef" rowSelection="multiple">
    </AgGridVuesCopys> -->
        <a-drawer :drawer-style="{ 'zIndex': 9999 }" :mask-closable="false" :width="400" :visible="pageData.showAdd"
            unmountOnClose @ok="sideOk" @cancel="pageData.showAdd = false" cancel-text='关闭' ok-text='保存'>
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-form ref="formRef" :model="dataForm">
                    <!-- <a-form-item label="序号" field="serialNumber" :rules="[{ required: true, message: '序号必填' }]"
                    :validate-trigger="['change', 'blur']" label-col-flex="68px">
                    <a-input-number v-model="dataForm.serialNumber" class="input-demo" :min="0"
                        :max="1000000000000000000000000000000000" />
                </a-form-item> -->
                    <a-form-item label="生产方式" field="productionMode" :validate-trigger="['change', 'blur']"
                        :rules="[{ required: true, message: '生产方式必填' }]" label-col-flex="80px">
                        <!-- <a-select popup-container="html"  :loading="loading" :allowClear="true" @search="handleSearch"
                        v-model="dataForm.productionMode" :filter-option="false" allow-search @focus="focusSel">
                        <a-option v-for="item in pageData.clothList" :value="item.productionMode">{{
                                item.productionMode
                        }}</a-option>
                    </a-select> -->
                        <a-input v-model="dataForm.productionMode" class="bacClass" />
                    </a-form-item>
                    <a-form-item label="备注" field="remark" label-col-flex="80px">
                        <a-textarea v-model="dataForm.remark" default-value="" class="bacClass" />
                    </a-form-item>
                </a-form>
            </div>
        </a-drawer>
    </div>
</template>

<script lang="ts">
import { post, get } from "@/api/http";
import { Search, CirclePlus, Delete } from "@element-plus/icons-vue";
import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
} from "@/hooks/table";

import { ref, reactive, onMounted, onActivated, onUnmounted } from "vue";
import Toolbar from "@/components/Toolbar.vue";
import { Form, Message, Modal, Pagination } from "@arco-design/web-vue";
import { FormInstance } from "@arco-design/web-vue/es/form";
import emitter from "@/hooks/useEventBus";
import validate from "@/hooks/useValidate";
//import { baseURL } from '../../../api/axios.config'
import axios from "axios";
import filedownload from 'js-file-download'
import "ag-grid-community/styles/ag-grid.css";
import "ag-grid-community/styles/ag-theme-alpine.css";
import {  } from "ag-grid-vue3";
//import aag from "./AGbut"
//import aag from "./agbuut.vue"
interface ClothSet {
    id?: any;
    serialNumber?: number | undefined,
    mercery?: string | undefined;
    deleteState?: any
    remark?: string | undefined;
    productionMode?: string | undefined;
    createName?: string | undefined;
    createTime?: string | undefined;
    updateName?: string | undefined;
    updateTime?: string | undefined;
}
interface pagings {
    size: number | string,
    total: number | string,
}
export default {
    name: "productionMode",
    setup() {
        //  const headerShow = ref<boolean>(true)
        //查询
        const scrollbar = ref(true)
        const pages = ref(1);
        const paging: pagings = reactive({
            size: 10,
            total: 30,
        })
        function doRefresh() {

            pageData.pageLoading = true

            post({
                url: "/aps/ProductionMode/selectPage",
                data: {
                    page: pages.value,
                    limit: paging.size,
                    productionMode: "",
                    remark: "",
                    deleteState: 0
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        //  console.log(data, "结果");
                        tableCon.tableConter = data.data;
                        paging.total = data.total;
                        //     // pagination.setTotalSize(data.total);

                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }

        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        //检验表单是否含有中文的方法
        const hasChiese = validate.includeChinese;
        // const columns = [
        //     {
        //         title: '顺号',
        //         key: "sequence",
        //         width: 150,
        //         align: "center",
        //         dataIndex: 'sequence',
        //     },
        //     {
        //         title: '生产方式',
        //         key: "productionMode",
        //         width: 150,
        //         dataIndex: 'productionMode',
        //         align: "center"
        //     },
        //     {
        //         title: '备注',
        //         key: "remark",
        //         width: 150,
        //         dataIndex: 'remark',
        //         align: "center"
        //     },
        //     {
        //         title: '建立人',
        //         key: "createName",
        //         width: 150,
        //         dataIndex: 'createName',
        //         align: "center"
        //     },
        //     {
        //         title: '建立时间',
        //         key: "createTime",
        //         width: 150,
        //         dataIndex: 'createTime',
        //         align: "center"
        //     },
        //     {
        //         title: '修改人',
        //         key: "updateName",
        //         width: 150,
        //         dataIndex: 'updateName',
        //         align: "center"
        //     },
        //     {
        //         title: '修改时间',
        //         key: "updateTime",
        //         width: 150,
        //         dataIndex: 'updateTime',
        //         align: "center"
        //     },
        //     {
        //         title: '操作',
        //         key: "id",
        //         width: 150,
        //         dataIndex: 'id',
        //         slotName: "action",
        //         fixed: 'right',
        //         align: "center"
        //     },
        // ];
        const columns = [
            {
                title: '',
                key: "check",
                width: 50,
                align: "center",
                dataIndex: 'check',
                checkboxSelection: true,
                headerCheckboxSelection: true,
                pinned: 'left',
            },
            {
                title: '生产方式',
                key: "productionMode",
                width: 200,
                dataIndex: 'productionMode',
                align: "center"
            },
            {
                title: '备注',
                key: "remark",
                width: 200,
                dataIndex: 'remark',
                align: "center"
            },
            {
                title: '建立人',
                key: "createName",
                width: 200,
                dataIndex: 'createName',
                align: "center"
            },
            {
                title: '建立时间',
                key: "createTime",
                width: 200,
                dataIndex: 'createTime',
                align: "center"
            },
            {
                title: '修改人',
                key: "updateName",
                width: 150,
                dataIndex: 'updateName',
                align: "center"
            },
            {
                title: '修改时间',
                key: "updateTime",
                width: 200,
                dataIndex: 'updateTime',
                align: "center"
            },
            {
                title: '操作',
                key: "edit",
                width: 150,
                dataIndex: 'edit',
                slotName: "edit",
                fixed: 'right',
                align: "center"
            },
        ];
        /************************************** */
        const columnDefs = [
            {
                headerName: '',//选择列头部显示的文字，可以为空
                checkboxSelection: true,//设置为ture显示为复选框
                headerCheckboxSelection: true, //表头是否也显示复选框，全选反选用
                pinned: 'left', //固定再左边
                width: 50 //列的宽度
            },
            { headerName: "生产方式", field: "productionMode", },
            { headerName: "备注", field: "remark" },
            { headerName: "建立人", field: "createName" },
            { headerName: "建立时间", field: "createTime", },
            { headerName: "修改人", field: "updateName" },
            { headerName: "修改时间", field: "updateTime" },
            { headerName: "操作", },

        ];
        const rowData = [
            { make: "Toyota", model: "Celica", price: 35000 },
            { make: "Ford", model: "Mondeo", price: 32000 },
            { make: "Porsche", model: "Boxster", price: 72000 },
            { make: "Toyota", model: "Celica", price: 35000 },
            { make: "Ford", model: "Mondeo", price: 32000 },
            { make: "Porsche", model: "Boxster", price: 72000 },
            { make: "Toyota", model: "Celica", price: 35000 },
            { make: "Ford", model: "Mondeo", price: 32000 },
            { make: "Porsche", model: "Boxster", price: 72000 },
        ];
        const defaultColDef = {
            sortable: true,
            filter: true,
            flex: 1,
            resizable: true,
        };
        let tc: any[] = columnDefs.map((o) => {
            //let obj = {}
            if (o.headerName === '操作') {
                o['resizable'] = false
                o['filter'] = false
                o['sortable'] = false
                o["pinned"] = "right"
                o["width"] = 80
                o['cellRenderer'] = {
                    template: `<el-button style="color:#165dff;"  link  @click="a">修改</el-button>`,
                    setup(props: any) {
                        const a = () => {
                            editHandler(props.params.data)
                        }
                        return {
                            a
                        }
                    }

                }
            }
            return o
        })
        const gridOption = ref()
        const gridReady = (params: any) => {
            console.log(params, 123321);
            gridOption.value = params.api
        }
        /***************************************** */
        const tableCon = reactive({
            tableConter: []
        });
        //页改变
        const pagingChange = (current: number) => {
            // console.log(current, "分页改变");
            pages.value = current;
            doRefresh();
        }
        //页条改变
        const pagingSizeChange = (pageSize: number) => {
            //  console.log(pageSize, "条数")
            pages.value = 1;
            paging.size = pageSize;
            doRefresh();
        }
        const alone = (rowKeys, rowKey, record) => {
            // console.log(rowKeys);
            // console.log(rowKey);
            // console.log(record);
        }
        const alonell = (selected, selectedRows,) => {
            // console.log(selected);
            // console.log(selectedRows);
        }
        const scroll = {
            x: 2000,
            y: 200
        };
        const tablediv = ref(null)
        const pageData = reactive<{
            clothList: ClothSet[]
            showAdd: boolean
            sideTitle: string
            dropDownData: any
            pageLoading: boolean,
            theight: number,
            tablediv: any,
            rHeight: number | undefined
        }>({
            clothList: [],
            showAdd: false,
            sideTitle: "新增资料",
            dropDownData: "",
            pageLoading: false,
            theight: 0,
            tablediv: null,
            rHeight: 0
        });
        //下拉框得到焦点
        const focusSel = () => {
            selCxAll({ productionMode: "" })
        }
        //下拉数据
        const options = ref<any>(pageData.clothList);
        const loading = ref(false);
        const handleSearch = (value: any) => {
            if (value) {
                const ob = { productionMode: value }
                loading.value = true;
                selCxAll(ob);
                options.value = pageData.clothList;
                loading.value = false;
            } else {
                options.value = []
            }
        };

        //下拉框查询
        function selCxAll(val: any) {
            post({
                url: "/aps/ProductionMode/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                // console.log(data,"下拉返回");
                if (code === 200) {
                    pageData.clothList = data;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }

        onMounted(() => {
            doRefresh();

        });
        //查询
        const selectHandler = () => {
            pages.value = 1;
            doRefresh();
            // console.log(paging, 5555555555555)
            // console.log(pages.value, 999999999999)
        }
        const queryData = reactive({
            clothType: "",
        });
        const addHandler = () => {
            for (var key in dataForm) {
                if (key === "id") {
                    dataForm[key] = null;
                } else if (key == 'serialNumber') {
                    dataForm[key] = 0;
                }
                else {
                    dataForm[key] = "";
                }

            }
            pageData.showAdd = true;
            pageData.sideTitle = "新增资料";
        };
        const dataForm = reactive<ClothSet>({
            id: null,
            remark: "",
            productionMode: ""
        });
        const formRef = ref<FormInstance>();
        const sideOk = () => {
            formRef.value?.validate().then((err) => {
                if (!err) {
                    if (pageData.sideTitle === "新增资料") {
                        post({
                            url: "/aps/ProductionMode/insert",
                            data: [dataForm],
                        }).then((res: any) => {
                            // console.log(res,"新增返回结果");
                            if (res.code === 200) {
                                formRef.value?.resetFields();
                                pageData.showAdd = false;
                                Message.success({
                                    content: "新增成功",
                                    duration: 5000,
                                });
                                doRefresh();
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }

                        });
                    } else {
                        post({
                            url: "/aps/ProductionMode/update",
                            data: [dataForm],
                        }).then((res: any) => {
                            // console.log(res, "修改返回");
                            if (res.code === 200) {
                                formRef.value?.resetFields();
                                pageData.showAdd = false;

                                Message.success({
                                    content: "修改成功",
                                    duration: 5000,
                                });
                                doRefresh();
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }

                        });
                    }
                }
            });
        };
        const deleteHandler = () => {
            // console.log(selectedRowKeys.value, 888888888)
            var arr = [];
            arr = gridOption.value.getSelectedRows().map((item) => {
                return item.id
            })
            //console.log(gridOption.value.getSelectedRows(), "lkj");
            if (arr.length === 0) {
                Message.warning({
                    content: "请选择要删除的数据",
                    duration: 5000,
                });
                return;
            }
            // console.log(arrs);
            Modal.confirm({
                title: "系统提示",
                content: "确认删除选中的数据?",
                onOk() {
                    post({
                        url: "/aps/ProductionMode/delete",
                        data: arr,
                    }).then(({ code, data }: any) => {
                        // console.log(code,"删除的状态码")
                        if (code === 200) {
                            Message.success({
                                content: "删除成功",
                                duration: 5000,
                            });
                            pages.value = 1;
                            doRefresh();
                        } else {
                            Message.error({
                                content: "删除失败",
                                duration: 5000,
                            });
                        }
                        selectedRowKeys.value = [];
                    });
                },
            });
        };
        const editHandler = (record: ClothSet) => {
            for (var key in record) {
                dataForm[key] = record[key]
            }
            pageData.sideTitle = '修改资料'
            pageData.showAdd = true
        };


        //导出
        const exports = () => {
            if (selectedRowKeys.value.length === 0) {
                Message.error('请先勾选')
                return
            } else {
                //将表头拼接出来
                let head = "<th>编号</th><th>名称</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
                //拿到当前表格数据与勾选的行做筛选

                let nowRow = table.dataList.filter(function (o) {
                    return selectedRowKeys.value.indexOf(o["id"]) !== -1;
                })
                let body = "";
                nowRow.forEach(function (o) {
                    body += "<tr><td>" + o["merceryCode"] + "</td>";
                    body += "<td>" + o["merceryName"] + "</td>";
                    body += "<td>" + o["remark"] + "</td>";
                    body += "<td>" + o["createName"] + "</td>";
                    body += "<td>" + o["createTime"] + "</td>";
                    body += "<td>" + o["updateName"] + "</td>";
                    body += "<td>" + o["updateTime"] + "</td>";
                    body += "</tr>";
                })
                tableToXlsx(head, '布类资料', body)
                //  console.log(table)
            }
        }

        function tableToXlsx(head: any, filename: any, body: any) {
            const uri = 'data:application/vnd.ms-excel;base64,',
                template = `<html>
          <head><meta charset="UTF-8"></head>
          <body><table border="1"><tr>${head}</tr>${body}</table></body>
      </html>`;

            const a = document.createElement('a');
            a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
            a.download = filename;
            a.click();
            document.removeChild(a);
        }

        //模板下载
        const downloadHandler = () => {
            axios.get(baseURL + '/product/mercery/uploadMerceryModel', {
                responseType: 'blob',
                headers: {
                    token: sessionStorage.getItem('USER-TOKEN-KEY')
                }
            }).then((res) => {
                if (res.status === 200) {
                    filedownload(res.data, '布类资料.xlsx')
                }
            })
        }
        //导入
        const importHandler = () => {

            const inputEle: HTMLInputElement = document.createElement('input')
            inputEle.type = 'file'
            inputEle.id = 'fileUploadExcel'
            inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
            inputEle.addEventListener('change', (e) => {
                const formData = new FormData()
                if (inputEle.files !== null) {
                    formData.append('file', inputEle.files[0] || '')
                } else {
                    Message.warning('未选择文件！');
                    return
                }
                pageData.pageLoading = true
                axios.post(baseURL + '/product/mercery/analyseMerceryModel', formData, {
                    headers: {
                        "Content-Type": 'multipart/form-data',
                        "token": sessionStorage.getItem('USER-TOKEN-KEY')
                    },
                }).then((result) => {
                    if (result.data['code'] === 200) {
                        Message.success('导入成功')
                    } else {
                        Message.error(result.data.message)
                    }

                }).finally(() => {
                    pageData.pageLoading = false
                    doRefresh()
                })
            })
            inputEle.click()
        }
        return {
            alone,
            alonell,
            scroll,
            scrollbar,
            tablediv,
            downloadHandler,
            importHandler,
            hasChiese,
            deleteHandler,
            sideOk,
            formRef,
            dataForm,
            addHandler,
            selectedRowKeys,
            pagination,
            // tableColumns,
            table,
            columns,
            tableCon,
            rowKey,
            pageData,
            queryData,
            editHandler,
            selectHandler,
            options,
            loading,
            handleSearch,
            exports,
            focusSel,
            paging,
            pagingChange,
            pagingSizeChange,
            // headerShow
            pages,
            /**************** */
            rowData,
            defaultColDef,
            columnDefs,
            tc,
            gridReady,
            gridOption,
            /************************ */
            Search,
            CirclePlus,
            Delete
        };
    },
    components: { Toolbar, },
};
</script>
<style  lang="less">
.pagings {
    margin-top: 10px;
    display: flex;
    justify-content: center;
}

.arco-input-wrapper {
    background-color: #fff !important;
    border: 1px solid #cccccc;
}

.arco-form-item-status-error .arco-input-wrapper:not(.arco-input-disabled),
.arco-form-item-status-error .arco-textarea-wrapper:not(.arco-textarea-disabled) {
    border: 1px solid #f53f3f;
}
/********************************************** */
.stbutencx {
    background-color: #409eff;

    &:hover {
        background-color: #79bbff;
    }
}

.ag-header-cell-resize::after {
    top: 0 !important;
    height: 100% !important;
}

.ag-cell {
    border-right: 1px solid #D9DDDF !important;
}

.stbutenxz {
    background-color: #67c23a;

    &:hover {
        background-color: #b3e19d;
    }
}
/************************************************** */
</style>